﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;

namespace SPWebShell.cmdlet
{
    /*
     * returns the absolute URL to a Web given any url to an item or folder in this site
     */ 
    [Cmdlet(VerbsCommon.Get, "WebUrlFromAnyUrl")]
    public class GetSiteUrlFromAnyUrl : CmdLetBase
    {
        [Parameter(Mandatory = true, HelpMessage = "The absolute URL of an item or folder on the web site whose complete URL will be returned . e.g. http://server/sites/SiteA/lists/Tasks/")]
        [ValidateNotNullOrEmpty]
        public string Url { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                WriteVerbose("Start time: " + DateTime.Now.ToString());
                WriteVerbose("Verifying if URL has right shape" + this.Url);
                Uri u = new Uri(this.Url);
                WriteVerbose("URL looks fine");
                ISPRepository repos = base.SPRepos;
                WriteVerbose("Before calling method GetContainerWebFromDocLibUrl");
                string urlSite=repos.GetContainerWebFromDocLibUrl(this.Url);
                WriteVerbose("After calling method GetContainerWebFromDocLibUrl");
                WriteObject(urlSite);
                base.ProcessRecord();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                string message = ex.Detail.OuterXml;
                throw new Exception(message, ex);
            }
            catch (System.Exception ex)
            {
                throw;
            }
            finally
            {
                WriteVerbose("End time: " + DateTime.Now.ToString());
            }
            
        }
    }
}
